package function.playlist;

import java.io.IOException;

import tool.DBFileUtils;
import boot.Boot;
import db.DBListener;
import db.DBReader;
import db.Mp3DBRecord;
import function.Mp3File;


public class DBPlaylist extends SimplePlaylist {

	private String dbFilePath;
	private Mp3File mp3;

	public DBPlaylist(String genre) {
		super(genre);
		dbFilePath = DBFileUtils.getDBPath(genre);
	}

	public Mp3File getMp3(int index) {
		DBReader dbReader = new DBReader(dbFilePath);
		dbReader.addListener(new InnerListener(index, dbReader));
		dbReader.readDB();
		return mp3;
	}
	
	private class InnerListener implements DBListener {

		private int index;
		private int count;
		private DBReader reader;

		public InnerListener(int anIndex, DBReader aReader) {
			reader = aReader;
			index = anIndex;
			count = 0;
		}
		
		public void processRecord(Mp3DBRecord record) {
			if (count == index) {
				mp3 = record.getMp3File();
				try {
					reader.stopReading();
				} catch (IOException e) {
					Boot.alertException(e, this, "InnerListener.processRecord()");
				}
			} else if (count < index) {
				count++;
			}
		}

		public void readingDone() {
			// Do nothing
		}
		
	}
	
}
